import Access from '@/components/Access';
import type { ActionType, ProColumns } from '@/components/Pro';
import { ProTable } from '@/components/Pro';
import {
  emsComponentControllerGetEmsComponentList as TableList,
  emsComponentControllerUpgradeIssuance as revert,
} from '@/services/ess/emsComponent';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';
import { useModel } from '@@/exports';

import { Button, CascaderProps, GetProp, message, Modal, Space } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { history, Link, useIntl } from 'umi';
type DefaultOptionType = GetProp<CascaderProps, 'options'>[number];

const getTenantOptions = (options: any) => {
  const treeData = [];
  function getTreeChildren(stationOptions: any[]) {
    return stationOptions.map((item) => {
      return {
        label: item.stationName,
        value: item.id,
      };
    });
  }

  options.forEach((item) => {
    treeData.push({
      value: item.tenantName,
      label: item.tenantName,
      children: getTreeChildren(item.stationInfos),
    });
  });
  return treeData;
};
const filter = (inputValue: string, path: DefaultOptionType[]) => {
  return path.some((option) => {
    const label = option.label as string;
    return label.toLowerCase().includes(inputValue.toLowerCase()) && path.length === 2;
  });
};

const getInitialValueByStationId = (stationId: string, options: any[]) => {
  for (const tenant of options) {
    const station = tenant.children?.find((item: any) => item.value === Number(stationId));
    if (station) {
      return [tenant.label, station.value];
    }
  }
  return [options[0]?.label, options[0]?.children[0]?.value];
};

const UpgradeManagement: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const actionRef = useRef<ActionType>();
  const { confirm } = Modal;
  const tenantOptions = getTenantOptions(initialState?.tenants);
  const [stationsName, setstationsName] = useState(tenantOptions[0]?.children[0]?.label);
  const [stationId, setStationId] = useState('');
  const [disableSearch, setDisableSearch] = useState<boolean>(false); // 控制查询按钮禁用状态

  const [searchCollapsed, setSearchCollapsed] = useState(false);
  const intl = useIntl();
  console.log(intl);
  const tableColumns: ProColumns[] = [
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.generalProcedure.SN' }),
      dataIndex: 'pageIndex',
      valueType: 'index',
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.componentManagement.selectPlant' }),
      dataIndex: 'stationId',
      key: 'stationId',
      valueType: 'cascader',
      hideInTable: true,
      fieldProps: {
        options: tenantOptions,
        changeOnSelect: true,
        allowClear: false,
        showSearch: { filter },
        defaultValue: getInitialValueByStationId(
          initialState?.stationId?.toString() || '',
          tenantOptions,
        ),
        onChange: (value, selectedOptions) => {
          if (selectedOptions && selectedOptions.length < 2) {
            setDisableSearch(true);
            setStationId('');
          } else {
            const stationObj = tenantOptions.find((res) => res.label === value[0])?.children;
            const name = stationObj?.find((res) => res.value === value[1]);
            setstationsName(name?.label || '');
            setStationId(value.at(-1));
            setDisableSearch(false);
          }
        },
      },
      search: {
        transform: (value) => {
          return {
            stationId: value.at(-1),
          };
        },
      },
    },
    {
      title: intl.formatMessage({
        id: 'remoteUpgradeMangment.siteConfigurationManagement.updateTime',
      }),
      dataIndex: 'updatedTime',
      key: 'updatedTime',
      width: 150,
      valueType: 'dateTimeRange',
      colSize: 2,
      render: (_, record) => {
        return <span>{record.updatedTime}</span>;
      },
      search: {
        transform: (value) => {
          return {
            queryStartTime: value[0],
            queryEndTime: value[1],
          };
        },
      },
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgrade.collectionPoint' }),
      dataIndex: 'stationTrmName',
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.componentManagement.componentType' }),
      dataIndex: 'componentType',
      key: 'componentType',
      valueType: 'select',
      request: async () => {
        return await fetchDictInfo(DATABASE_TYPE_ENUM.COM_TYPE);
      },
    },
    {
      title: intl.formatMessage({
        id: 'remoteUpgradeMangment.componentManagement.componentNameNotitle',
      }),
      dataIndex: 'componentName',
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.componentManagement.versionNumber' }),
      dataIndex: 'version',
      hideInSearch: true,
    },

    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.componentManagement.operation' }),
      hideInSearch: true,
      dataIndex: 'operation',
      key: 'operation',
      render: (_, record) => {
        const handleLinkClick = () => {
          const EmsComponentParams = {
            componentName: record?.componentName,
            stationsName: stationsName,
            stationId: record?.stationId,
            componentId: record?.componentId,
            version: record?.version,
            componentType: record?.componentType,
            time: record?.updatedTime,
            stationComponentId: record?.id,
          };
          sessionStorage.setItem('EmsComponentParams', JSON.stringify(EmsComponentParams));
        };

        return (
          <Space>
            <Access perm={'remote:maintenance'} key={'link'}>
              <Link
                to={`/remoteUpgrade/remoteMaintenance/ota/update`}
                id="updateLink"
                onClick={handleLinkClick}
                data-componentid={record?.componentId}
              >
                <span>
                  {intl.formatMessage({
                    id: 'remoteUpgradeMangment.siteConfigurationManagement.update',
                  })}
                </span>
              </Link>
            </Access>

            <a
              onClick={async () => {
                confirm({
                  title: intl.formatMessage({ id: 'systemManagement.supplementary.prompt' }),
                  content: `${intl.formatMessage({
                    id: 'remoteUpgradeMangment.other.afterRollback',
                  })},${intl.formatMessage({
                    id: 'remoteUpgradeMangment.other.doYouWantToRollback',
                  })}`,
                  onOk() {
                    let params = {
                      stationComponentId: record?.id,
                      pkgId: record?.id,
                      instructionType: 'ROLLBACK',
                    };

                    let timer = null;
                    revert(params, { stationId: stationId }).then((reslut) => {
                      if (reslut.success) {
                        message.success(
                          intl.formatMessage({
                            id: 'remoteUpgradeMangment.other.rollbacking',
                          }),
                        );
                        actionRef.current?.reloadAndRest?.();
                        // 清除之前的定时器
                        if (timer) {
                          clearTimeout(timer);
                        }
                        timer = setTimeout(() => {
                          const updateLink = document.querySelector(
                            `a[data-componentid="${record?.componentId}"]`,
                          );
                          if (updateLink) {
                            updateLink.click();
                          }
                        }, 1000);
                      }
                    });
                  },
                  onCancel() {},
                });
              }}
            >
              {intl.formatMessage({ id: 'remoteUpgradeMangment.other.rollback' })}
            </a>
          </Space>
        );
      },
    },
  ];

  const handleToggleSearch = () => {
    setSearchCollapsed(!searchCollapsed);
  };

  useEffect(() => {
    getTenantOptions(initialState?.tenants);
  }, []);

  useEffect(() => {
    if (initialState?.stationId) {
      const initialValues = getInitialValueByStationId(
        initialState.stationId.toString(),
        tenantOptions,
      );
      setstationsName(initialValues[1]);
      setStationId(initialValues[1]);
    }
  }, [initialState?.stationId]);

  // 从 sessionStorage 获取参数
  const params = JSON.parse(sessionStorage.getItem('EmsComponentParams') || '{}');

  const handleBack = () => {
    // 使用原始的站点 ID 返回
    const stationId = params.stationId;
    if (stationId) {
      history.push(`/remoteUpgrade/remoteMaintenance/detail?stationid=${stationId}`);
    } else {
      // 如果没有找到站点 ID，返回到列表页
      history.push('/remoteUpgrade/remoteMaintenance/list');
      message.warning(intl.formatMessage({ id: 'common.stationIdNotFound' }));
    }
  };

  return (
    <ProTable
      headerTitle={
        <Space>
          {intl.formatMessage({ id: 'maintenance.otaTitle' })}
          <Button onClick={handleBack} type="link" size="small">
            {intl.formatMessage({ id: 'remoteUpgrade.back' })}
          </Button>
        </Space>
      }
      actionRef={actionRef}
      rowKey={'pageIndex'}
      columns={tableColumns}
      request={async (values) => {
        let param = {
          ...values,
        };
        try {
          if (!disableSearch) {
            let reslut = await TableList(param, {
              stationId: values.stationId,
            });
            return reslut;
          } else {
            return false;
          }
        } catch (error) {}
      }}
      search={{
        collapsed: searchCollapsed,
        onCollapse: handleToggleSearch,
      }}
    />
  );
};

export default UpgradeManagement;
